package org.zhang.service;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zhang.common.Result;
import org.zhang.entity.User;
import org.zhang.exception.ServiceException;
import org.zhang.mapper.UserMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者:小张
 * 日期:2024/5/21 10:55
 */

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public void insertUser(User user) {

        userMapper.insert(user);
    }

    public void updataUser(User user) {
        userMapper.updataUser(user);

    }

    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    public User selectById(Integer id) {

        return userMapper.selectById(id);

    }

    public List<User> selectMores(String name, String gender) {
        return userMapper.selectMores(name, gender);
    }

    public List<User> selectByLike(String name, String gender) {

        return userMapper.selectByLike(name, gender);
    }

    public Result login(User user) {
        //去除前后可能存在的空格
        user.setName(user.getName().trim());
        user.setPassword(user.getPassword().trim());
        //判断用户明密码不能为空
        if (StrUtil.isBlank(user.getName()) || StrUtil.isBlank(user.getPassword())) {
            return Result.error("账号密码不能为空");
        }
        //根据用户查询数据库的用户信息
        User dbUser = userMapper.selectByName(user.getName());
        if (dbUser == null) {
            return Result.error("用户不存在");
        }
        System.err.println(user);
        System.err.println(dbUser);
        if (dbUser.getPassword().equals(user.getPassword())){
            return Result.success(null);
        }
        return Result.error("密码错误");
    }

    public Result register(User user) {
        //去除前后可能存在的空格
        user.setName(user.getName().trim());
        user.setPassword(user.getPassword().trim());
        //判断用户明密码不能为空
        if (StrUtil.isBlank(user.getName()) || StrUtil.isBlank(user.getPassword())) {
            return Result.error("账号密码不能为空");
        }
        User user1 = userMapper.selectByName(user.getName());
        if (user1 != null){
            return Result.error("账号已存在！");
        }
        userMapper.insert(user);
        return Result.success(null);

    }
}
